import { i18n } from "./i18n";
import { router } from "./router";
import { getToken, getKey } from "./auth";
import { UserStore } from '@/store/user';

const { t } = i18n.global;

router.beforeEach((to, from) => {
  const store = UserStore();
  const toDepth = to.path.split("/").length;
  const fromDepth = from.path.split("/").length;
  to.meta.transition = toDepth < fromDepth ? "slide-right" : "slide-left";

  const title = to.meta.title;
  const token = getToken();
  const key = getKey('isCheck');
  
  if (!key && to.name !== "check") {
    return "/check"
  }

  if (key && to.name == 'check') {
    return from.path ? from.path : "/";
  }

  
  if (to.name !== "login" && to.name !== "register" && to.name !== "check" && to.name !== "test" && !token) {
    console.log("去登录-注册");
    return "/login";
  }
  //   防止重复登录
  if (to.path == "/login" && token) {
    return `/`;
  }
  
  const toPath = to.path;
  switch (toPath) {
    case '/':
      store.curIndex = 0;
      break;
    case '/self':
      store.curIndex = 1;
      break;
    case '/market':
      store.curIndex = 2;
      break;
    case '/news':
      store.curIndex = 3;
      break;
    case '/mine':
      store.curIndex = 4;
      break;
  
    default:
      break;
  }

  if (token) store.getUserInfo();
  if (title == 'Detail') {
    document.title = to.query.pairsName;
  } else {
    document.title = t(title);
  }
});
